{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Amazon AgentCore Bedrock Code Interpreter Tutorial\n",
    "\n",
    "This tutorial demonstrates how to use AgentCore Bedrock Code Interpreter to:\n",
    "1. Set up a sandbox environment\n",
    "2. Load and analyze data\n",
    "3. Execute code in a sandbox environment\n",
    "4. Process and retrieve results\n",
    "\n",
    "## Prerequisites\n",
    "- AWS account with Bedrock AgentCore Code Interpreter access\n",
    "- You have the necessary IAM permissions to create and manage code interpreter resources\n",
    "- Required Python packages installed(including boto3 & bedrock-agentcore)\n",
    "- Sample data file (data.csv)\n",
    "- Analysis script (stats.py)\n",
    "\n",
    "\n",
    "## Your IAM execution role should have the following IAM policy attached"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "~~~ {\n",
    "    \"Version\": \"2012-10-17\",\n",
    "    \"Statement\": [\n",
    "        {\n",
    "            \"Effect\": \"Allow\",\n",
    "            \"Action\": [\n",
    "                \"bedrock-agentcore:CreateCodeInterpreter\",\n",
    "                \"bedrock-agentcore:StartCodeInterpreterSession\",\n",
    "                \"bedrock-agentcore:InvokeCodeInterpreter\",\n",
    "                \"bedrock-agentcore:StopCodeInterpreterSession\",\n",
    "                \"bedrock-agentcore:DeleteCodeInterpreter\",\n",
    "                \"bedrock-agentcore:ListCodeInterpreters\",\n",
    "                \"bedrock-agentcore:GetCodeInterpreter\"\n",
    "            ],\n",
    "            \"Resource\": \"*\"\n",
    "        },\n",
    "        {\n",
    "            \"Effect\": \"Allow\",\n",
    "            \"Action\": [\n",
    "                \"logs:CreateLogGroup\",\n",
    "                \"logs:CreateLogStream\",\n",
    "                \"logs:PutLogEvents\"\n",
    "            ],\n",
    "            \"Resource\": \"arn:aws:logs:*:*:log-group:/aws/bedrock-agentcore/code-interpreter*\"\n",
    "        }\n",
    "    ]\n",
    "}\n",
    "\n"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## How it works\n",
    "\n",
    "The code execution sandbox enables agents to safely process user queries by creating an isolated environment with a code interpreter, shell, and file system. After a Large Language Model helps with tool selection, code is executed within this session, before being returned to the user or agent for synthesis.\n",
    "\n",
    "![architecture local](code-interpreter.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Setting Up the Environment\n",
    "\n",
    "First, let's import the necessary libraries and initialize our Code Interpreter client."
   ]
  },
{
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "!pip install --upgrade -r requirements.txt"
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T04:01:17.925083Z",
     "start_time": "2025-07-13T04:01:16.036433Z"
    }
   },
   "source": [
    "from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter\n",
    "import json\n",
    "from typing import Dict, Any, List\n",
    "\n",
    "# Initialize the Code Interpreter with your AWS region\n",
    "code_client = CodeInterpreter('us-west-2')\n",
    "code_client.start()"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'01K00Z3F8WZ9KBBW4QGRJCVBHH'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 21
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Reading Local Files\n",
    "\n",
    "Now we'll read the contents of our sample data file and analysis script."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T04:01:17.953880Z",
     "start_time": "2025-07-13T04:01:17.942684Z"
    }
   },
   "source": [
    "def read_file(file_path: str) -> str:\n",
    "    \"\"\"Helper function to read file content with error handling\"\"\"\n",
    "    try:\n",
    "        with open(file_path, 'r', encoding='utf-8') as file:\n",
    "            return file.read()\n",
    "    except FileNotFoundError:\n",
    "        print(f\"Error: The file '{file_path}' was not found.\")\n",
    "        return \"\"\n",
    "    except Exception as e:\n",
    "        print(f\"An error occurred: {e}\")\n",
    "        return \"\"\n",
    "\n",
    "# Read both files\n",
    "data_file_content = read_file(\"samples/data.csv\")\n",
    "code_file_content = read_file(\"samples/stats.py\")"
   ],
   "outputs": [],
   "execution_count": 22
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Preparing Files for Sandbox Environment\n",
    "\n",
    "We'll create a structure that defines the files we want to create in the sandbox environment."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T04:01:17.966573Z",
     "start_time": "2025-07-13T04:01:17.964099Z"
    }
   },
   "source": [
    "files_to_create = [\n",
    "    {\n",
    "        \"path\": \"data.csv\",\n",
    "        \"text\": data_file_content\n",
    "    },\n",
    "    {\n",
    "        \"path\": \"stats.py\",\n",
    "        \"text\": code_file_content\n",
    "    }\n",
    "]"
   ],
   "outputs": [],
   "execution_count": 23
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Creating Helper Function for Tool Invocation\n",
    "\n",
    "This helper function will make it easier to call sandbox tools and handle their responses. Within an active session, you can execute code in supported languages (Python, JavaScript), access libraries based on your dependencies configuration, generate visualizations, and maintain state between executions."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T04:01:18.358299Z",
     "start_time": "2025-07-13T04:01:18.354409Z"
    }
   },
   "source": [
    "def call_tool(tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:\n",
    "    \"\"\"Helper function to invoke sandbox tools\n",
    "    \n",
    "    Args:\n",
    "        tool_name (str): Name of the tool to invoke\n",
    "        arguments (Dict[str, Any]): Arguments to pass to the tool\n",
    "        \n",
    "    Returns:\n",
    "        Dict[str, Any]: JSON formatted result\n",
    "    \"\"\"\n",
    "    response = code_client.invoke(tool_name, arguments)\n",
    "    for event in response[\"stream\"]:\n",
    "        return json.dumps(event[\"result\"])"
   ],
   "outputs": [],
   "execution_count": 24
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Writing Files to Sandbox\n",
    "\n",
    "Now we'll write our files into the sandbox environment and verify they were created successfully."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T04:01:26.265552Z",
     "start_time": "2025-07-13T04:01:20.088758Z"
    }
   },
   "source": [
    "# Write files to sandbox\n",
    "writing_files = call_tool(\"writeFiles\", {\"content\": files_to_create})\n",
    "print(\"Writing files result:\")\n",
    "print(writing_files)\n",
    "\n",
    "# Verify files were created\n",
    "listing_files = call_tool(\"listFiles\", {\"path\": \"\"})\n",
    "print(\"\\nFiles in sandbox:\")\n",
    "print(listing_files)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing files result:\n",
      "{\"content\": [{\"type\": \"text\", \"text\": \"Successfully wrote all 2 files\"}], \"isError\": false}\n",
      "\n",
      "Files in sandbox:\n",
      "{\"content\": [{\"type\": \"resource_link\", \"uri\": \"file:///log\", \"name\": \"log\", \"description\": \"Directory\"}, {\"type\": \"resource_link\", \"mimeType\": \"text/csv\", \"uri\": \"file:///data.csv\", \"name\": \"data.csv\", \"description\": \"File\"}, {\"type\": \"resource_link\", \"mimeType\": \"text/x-python\", \"uri\": \"file:///stats.py\", \"name\": \"stats.py\", \"description\": \"File\"}, {\"type\": \"resource_link\", \"uri\": \"file:///.ipython\", \"name\": \".ipython\", \"description\": \"Directory\"}], \"isError\": false}\n"
     ]
    }
   ],
   "execution_count": 25
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Executing Analysis\n",
    "\n",
    "Now we'll execute our analysis script in the sandbox environment and process the results."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T04:01:35.818531Z",
     "start_time": "2025-07-13T04:01:34.446242Z"
    }
   },
   "source": [
    "import pprint\n",
    "\n",
    "# Execute the analysis script\n",
    "code_execute_result = call_tool(\"executeCode\", {\n",
    "    \"code\": files_to_create[1]['text'],\n",
    "    \"language\": \"python\",\n",
    "    \"clearContext\": True\n",
    "})\n",
    "\n",
    "# Parse and display results\n",
    "analysis_results = json.loads(code_execute_result)\n",
    "print(\"Full analysis results:\")\n",
    "pprint.pprint(analysis_results)\n",
    "\n",
    "print(\"\\nStandard output from analysis:\")\n",
    "print(analysis_results['structuredContent']['stdout'])"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Full analysis results:\n",
      "{'content': [{'text': 'Name   Place  Animal   Thing\\n'\n",
      "                      'count       299130  299130  299130  299130\\n'\n",
      "                      'unique        1722      55      50      51\\n'\n",
      "                      'top     Lisa White  Prague    Goat  Pencil\\n'\n",
      "                      'freq           222    5587    6141    6058',\n",
      "              'type': 'text'}],\n",
      " 'isError': False,\n",
      " 'structuredContent': {'executionTime': 0.7111423015594482,\n",
      "                       'exitCode': 0,\n",
      "                       'stderr': '',\n",
      "                       'stdout': 'Name   Place  Animal   Thing\\n'\n",
      "                                 'count       299130  299130  299130  299130\\n'\n",
      "                                 'unique        1722      55      50      51\\n'\n",
      "                                 'top     Lisa White  Prague    Goat  Pencil\\n'\n",
      "                                 'freq           222    5587    6141    6058'}}\n",
      "\n",
      "Standard output from analysis:\n",
      "Name   Place  Animal   Thing\n",
      "count       299130  299130  299130  299130\n",
      "unique        1722      55      50      51\n",
      "top     Lisa White  Prague    Goat  Pencil\n",
      "freq           222    5587    6141    6058\n"
     ]
    }
   ],
   "execution_count": 26
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Cleanup\n",
    "\n",
    "Finally, we'll clean up by stopping the Code Interpreter session. Once finished using a session, the session should be shopped to release resources and avoid unnecessary charges."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-13T04:01:39.838014Z",
     "start_time": "2025-07-13T04:01:39.208092Z"
    }
   },
   "source": [
    "# Stop the Code Interpreter session\n",
    "code_client.stop()\n",
    "print(\"Code Interpreter session stopped successfully!\")"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Code Interpreter session stopped successfully!\n"
     ]
    }
   ],
   "execution_count": 27
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "In this tutorial, we've learned how to:\n",
    "- Initialize a Code Interpreter session\n",
    "- Read and prepare files for analysis\n",
    "- Execute code in a sandbox environment\n",
    "- Process and display results\n",
    "- Clean up resources"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
